#!/usr/bin/python
#
# Simple script to inhale a copy of the edit buffer for my aluminium
# gamer block and recalculate the various totals.
#

import math
import sys
import re
import StringIO

def CalculateAluminium(lines, extras = {}):

  counter_names = [ "received", "received-played", "played", "replayed", "given", "traded", "lastyear", "lastyear-played" ]
  counter = dict(zip(counter_names, [0] * len(counter_names)))

  output = StringIO.StringIO()

  total_lines = []
  section = None;
  total_comment = ""
  errors = ""
  non_blank_seen = False
  for line in lines:
    line = line.strip("\r\n")
    print_line = True
    if line.startswith("[b]"):
      l = line.lower()
      l = l.split("(")[0]
      if ((l.find("received") > 0) or
          (l.find("added") > 0) or
          (l.find("acqui") > 0)):
        section = "received"
      elif (l.find("2013") > 0) or (l.find("unplayed from") > 0):
        section = "lastyear"
      elif l.find("traded") > 0 or l.find("sold") > 0:
        section = "traded"
      elif l.find("given") > 0 or l.find("gift") > 0:
        section = "given"
      elif l.find("replayed") > 0:
        section = "replayed"
      elif l.find("played") > 0:
        section = "played"
      elif l.find("total") > 0:
        section = "total"
      else:
        section = ""
        errors += "Couldn't parse section " + line + "\n"
    elif section == "total":
      print_line = False
      total_lines.append(line.rstrip())
      m = re.search("\((.+)\)", line)
      if m:
        total_comment += m.group(1)
    elif not line.strip():
      pass
    elif not section:
      pass
    elif line.startswith("[-]"):
      if section not in [ "lastyear", "received" ]:
        pass
      else:
        counter[section + "-played"] += 1
    else:
      counter[section] += 1

    if print_line:
      print >>output, line

  total = (-counter["received"] + counter["lastyear-played"] +
           counter["played"] +
           3 * counter["given"] + counter["traded"] +
           0.2 * counter["replayed"])
  new_total_lines = []
  new_total_lines.append(
    ("%d received & unplayed @-1 each, %d from last years now played, "
     "%d old games played, %d traded/sold,  %d given away @+3 each, "
     "%d old games replayed @+0.2 each") % (
    counter["received"],
    counter["lastyear-played"],
    counter["played"],
    counter["traded"],
    counter["given"],
    counter["replayed"]))

  if abs(math.floor(total) - total) > 0.1:
    total_format = "Total: %.1f"
  else:
    total_format = "Total: %d"

  total_text = total_format % (total)
  if total_comment:
    total_text += " (%s)" % total_comment

  new_total_lines.append(total_text)

  # strip blank lines from the beginning and end.
  print >>output, ("\n".join(new_total_lines)).strip(),

  extras["new_total"] = "\n".join(new_total_lines) + "\n"
  if total_lines:
    extras["old_total"] = "\n".join(total_lines) + "\n"
  if errors:
    extras["errors"] = errors

  return output.getvalue()

def main():
  extras = {}
  lines = sys.stdin.readlines()

  print CalculateAluminium(lines, extras)
  if "errors" in extras:
    print extras["errors"]

  if "new_total" and "old_total" in extras:
    print >>sys.stderr, "Updated from:"
    print >>sys.stderr, extras["old_total"],
    print >>sys.stderr, "to:"
    print >>sys.stderr, extras["new_total"],

if __name__ == "__main__":
  main()
